#include "CTimer.h"

CTimer* CTimer::m_instance = NULL;
CTimer::CTimer(void)
{
	QueryPerformanceFrequency((LARGE_INTEGER*)&m_tickPerSecond);
	m_currentTime = m_lastTime = m_lastFPSUpdate = 0;
	m_numFrames = 0;
	m_runningTime = m_timeElapsed = m_fps = 0.0f;
	m_fpsUpdateInterval = m_tickPerSecond >>1;
	m_timerStoped = true;
}

CTimer::~CTimer(void)
{
}

CTimer* CTimer::GetInstance()
{
	if(m_instance == NULL)
	{
		m_instance = new CTimer();
	}
	return m_instance;
}

float CTimer::GetFPS()
{
	return m_fps;
}

float CTimer::GetRunningTime()
{
	return m_runningTime;
}

float CTimer::GetElapsedTime()
{
	return m_timerStoped ? 0.0f : m_timeElapsed;
}

bool CTimer::IsStopped()
{
	return m_timerStoped;
}

void CTimer::Start()
{
	if(!m_timerStoped)
	{
		// time was stopped
		return;
	}
	QueryPerformanceCounter((LARGE_INTEGER*)&m_lastTime);
	m_timerStoped = true;
}

void CTimer::Stop()
{
	if(m_timerStoped)
	{
		return;
	}
	INT64 stoppedTime = 0;
	QueryPerformanceCounter((LARGE_INTEGER*)&stoppedTime);
	m_runningTime += (float)(stoppedTime - m_lastTime)/(float)m_tickPerSecond;
	m_timerStoped = true;
}

void CTimer::Update()
{
	/*if(m_timerStoped)
	{
	return;
	}*/
	// Get the current time
	QueryPerformanceCounter((LARGE_INTEGER*)&m_currentTime);
	m_timeElapsed = (float)(m_currentTime - m_lastTime)/(float)m_tickPerSecond;
	m_runningTime += m_timeElapsed;

	// Update FPS
	m_numFrames++;
	if(m_lastTime - m_lastFPSUpdate >= m_fpsUpdateInterval)
	{
		float currentTime = (float)m_currentTime/(float)m_tickPerSecond;
		float lastTime = (float)m_lastFPSUpdate / (float)m_tickPerSecond;
		m_fps = (float)m_numFrames/(m_currentTime - m_lastTime);

		m_lastFPSUpdate = lastTime;
		m_numFrames = 0 ;
	}
	m_lastTime = m_currentTime;
}